import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
  	  todos: JSON.parse(localStorage.getItem('todo')) ? JSON.parse(localStorage.getItem('todo')) :[]
  },
  getters: {
  	total(state){
  		return state.todos.length;
    },
	  doneTolist(state){
  		return state.todos.reduce((pre, todo) => {
  			return pre+ (todo.done ? 1 : 0 )
	    }, 0)
	  },
	  isAllChecked(state, getters){
  		return getters.total> 0 && getters.total === getters.doneTolist
	  }
  },
  mutations: {
  	Add_todo(state, todoObj){
  		state.todos.unshift(todoObj);
	    localStorage.setItem('todo',JSON.stringify(state.todos) )
    },
	  Check_todo(state, id){
		  state.todos.forEach(todo => {
			  if(todo.id === id) todo.done = !todo.done;
		  });
		  localStorage.setItem('todo',JSON.stringify(state.todos) )
	  },
	  DELETE_TODO(state,id){
		  state.todos.splice(id,1);
		  localStorage.setItem('todo',JSON.stringify(state.todos) )
	  },
	  CHECK_ALL_TODO(state,done){
		  state.todos.forEach(todo => todo.done = done);
		  localStorage.setItem('todo',JSON.stringify(state.todos) )
	  },
	  CLEAR_ALL_TODO_DONE(state){
		  state.todos = state.todos.filter(todo => !todo.done);
		  localStorage.setItem('todo',JSON.stringify(state.todos) )
	  }
  },
  actions: {
  	// Lo(){
  	// 	localStorage.setItem('todo', )
    // }
  },
  modules: {},
});
